﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;

/// <summary>
/// Level control script.
/// </summary>
public class LevelManager : MonoBehaviour
{
    // UI scene. Load on level start
    public string levelUiSceneName;
    // Gold amount for this level
    public int goldAmount = 20;
    // How many times enemies can reach capture point before defeat
    public int defeatAttempts = 1;
    // List with allowed randomly generated enemy for this level
    public List<GameObject> allowedEnemies = new List<GameObject>();

    // User interface manager
    private UiManager uiManager;
    // Nymbers of enemy spawners in this level
    private int spawnNumbers;
    // Current loose counter
    private int beforeLooseCounter;

    //新增：自动生成每波怪物类型
    public GameObject enemyDog, enemyGoblin, enemyOrge, enemyOrc, enemyShaman, enemySTank, enemyVoodoo;
    private List<List<GameObject>> wavesEnemyPrefabs = new List<List<GameObject>>();
    private GameObject[] allEnemyPrefabs;
    public int totalWaves = 25;
    private int currentWave = 0;

    /// <summary>
    /// Awake this instance.
    /// </summary>
    void Awake()
    {
        // Load UI scene
        SceneManager.LoadScene(levelUiSceneName, LoadSceneMode.Additive);
    }

    /// <summary>
    /// Start this instance.
    /// </summary>
    void Start()
    {
        allEnemyPrefabs = new GameObject[] { enemyDog, enemyGoblin, enemyOrge, enemyOrc, enemyShaman, enemySTank, enemyVoodoo };
        // 配置25波敌人类型：只有5的倍数波有boss
        wavesEnemyPrefabs.Clear();
        for (int i = 1; i <= totalWaves; i++)
        {
            var enemyList = new List<GameObject>();
            int enemiesThisWave = Mathf.Clamp(3 + i / 2, 3, 15); // 自己调
            var pool = new List<GameObject> { enemyDog, enemyGoblin, enemyOrge, enemyOrc, enemyShaman };
            if (i % 5 == 0)
            { // 特殊波加STank和Voodoo
                pool.Add(enemySTank);
                pool.Add(enemyVoodoo);
            }
            for (int j = 0; j < enemiesThisWave; j++)
            {
                // 每种怪从池子里随机选1个，这样怪的总数会随波次递增
                var prefab = pool[Random.Range(0, pool.Count)];
                enemyList.Add(prefab);
                //enemyList.Add(prefab);
            }
            wavesEnemyPrefabs.Add(enemyList);
        }
        //设置波次间隔时间递增
        var wavesInfo = FindObjectOfType<WavesInfo>();
        wavesInfo.wavesTimeouts.Clear();

        float startTimeout = 5f;    // 第1波间隔5s
        float timeoutStep = 3f;      // 每3波递增3s

        for (int i = 0; i < totalWaves; i++)
        {
            float timeout = startTimeout + (i / 2) * timeoutStep;
            wavesInfo.wavesTimeouts.Add(timeout);
        }
        // 传递给所有SpawnPoint
        foreach (var spawnPoint in FindObjectsOfType<SpawnPoint>())
        {
            spawnPoint.SetWaves(wavesEnemyPrefabs);
        }
        uiManager = FindObjectOfType<UiManager>();
        SpawnPoint[] spawnPoints = FindObjectsOfType<SpawnPoint>();
        spawnNumbers = spawnPoints.Length;
        if (spawnNumbers <= 0)
        {
            Debug.LogError("Have no spawners");
        }
        // Set random enemies list for each spawner
        foreach (SpawnPoint spawnPoint in spawnPoints)
        {
            spawnPoint.randomEnemiesList = allowedEnemies;
        }
        Debug.Assert(uiManager, "Wrong initial parameters");
        // Set gold amount for this level
        uiManager.SetGold(goldAmount);
        beforeLooseCounter = defeatAttempts;
        uiManager.SetDefeatAttempts(beforeLooseCounter);
    }

    /// <summary>
    /// Raises the enable event.
    /// </summary>
    void OnEnable()
    {
        EventManager.StartListening("Captured", Captured);
        EventManager.StartListening("AllEnemiesAreDead", AllEnemiesAreDead);
        EventManager.StartListening("WaveStarted", OnWaveStarted);
    }

    /// <summary>
    /// Raises the disable event.
    /// </summary>
    void OnDisable()
    {
        EventManager.StopListening("Captured", Captured);
        EventManager.StopListening("AllEnemiesAreDead", AllEnemiesAreDead);
        EventManager.StopListening("WaveStarted", OnWaveStarted);
    }

    /// <summary>
    /// Enemy reached capture point.
    /// </summary>
    /// <param name="obj">Object.</param>
    /// <param name="param">Parameter.</param>
    private void Captured(GameObject obj, string param)
    {
        if (beforeLooseCounter > 0)
        {
            beforeLooseCounter--;
            uiManager.SetDefeatAttempts(beforeLooseCounter);
            if (beforeLooseCounter <= 0)
            {
                // Defeat
                uiManager.GoToDefeatMenu();
            }
        }
    }

    /// <summary>
    /// All enemies are dead.
    /// </summary>
    /// <param name="obj">Object.</param>
    /// <param name="param">Parameter.</param>
    private void AllEnemiesAreDead(GameObject obj, string param)
    {
        spawnNumbers--;
        if (spawnNumbers <= 0)
        {
            currentWave++; // 只有所有spawner都清空才+1，确保波数准确
            uiManager.GoToVictoryMenu();
        }
    }

    /// <summary>
    /// 真正开始每一波时触发的回调。param 里传的是波次数字字符串。
    /// </summary>
    private void OnWaveStarted(GameObject sender, string param)
    {
        if (int.TryParse(param, out int wave))
        {
            currentWave = wave;
            if (wave != 0 && wave % 5 == 0)
            {
                BuffRandomEnemies();
            }
        }
        else
        {
            Debug.LogWarning($"OnWaveStarted: 解析波次失败，param={param}");
        }
    }

    private void BuffRandomEnemies()
    {
        Debug.Log("【BuffRandomEnemies】尝试给敌人类型Prefab随机挂Buff");
        var buffTypes = new System.Type[] {
            typeof(RevivingEnemy),
            typeof(LowHealthShield),
            typeof(CloudOnDamage),
            typeof(AloneSpeedUp)
        };
        if (allEnemyPrefabs == null || allEnemyPrefabs.Length == 0)
        {
            Debug.LogError("【BuffRandomEnemies】allEnemyPrefabs 未初始化或为空！");
            return;
        }

        if (currentWave <= 0 || currentWave > wavesEnemyPrefabs.Count)
        {
            Debug.LogWarning("【BuffRandomEnemies】当前波次超出范围，不处理。");
            return;
        }

        var candidates = wavesEnemyPrefabs[currentWave - 1]
                          .Distinct()
                          .ToList();
        Debug.Log("【BuffRandomEnemies】本波候选类型：" +
                  string.Join(", ", candidates.Select(p => p.name)));

        int numToBuff = Mathf.Max(1, candidates.Count / 3);
        var rnd = new System.Random();
        var indices = new HashSet<int>();
        while (indices.Count < numToBuff)
        {
            indices.Add(rnd.Next(candidates.Count));
        }

        foreach (int idx in indices)
        {
            var prefab = candidates[idx];
            if (prefab == null)
            {
                Debug.LogError($"【BuffRandomEnemies】候选[{idx}]是 null，跳过");
                continue;
            }

            var buffType = buffTypes[rnd.Next(buffTypes.Length)];
            Debug.Log($"【BuffRandomEnemies】准备给 {prefab.name} 挂 Buff: {buffType.Name}");

            if (prefab.GetComponent(buffType) != null)
            {
                Debug.LogWarning($"【BuffRandomEnemies】{prefab.name} 已有 {buffType.Name}，不重复添加");
                continue;
            }

            var comp = prefab.AddComponent(buffType);
            if (comp != null)
            {
                string buffName = buffType.Name switch
                {
                    "RevivingEnemy" => "复活",
                    "LowHealthShield" => "残血护盾",
                    "CloudOnDamage" => "受伤放云",
                    "AloneSpeedUp" => "孤身加速",
                    _ => "特殊效果"
                };

                Debug.Log($"【BuffRandomEnemies】{prefab.name} 获得效果：{buffName}");

                // 新增：将Buff名称添加到UnitInfo组件
                var unitInfo = prefab.GetComponent<UnitInfo>();
                if (unitInfo != null)
                {
                    unitInfo.buffs.Add(buffName); // 关键修改：存储Buff信息
                }
                else
                {
                    Debug.LogError($"【BuffRandomEnemies】{prefab.name} 缺少UnitInfo组件，无法记录Buff");
                }

                uiManager?.ShowBuffNotice($"{prefab.name} 获得效果：{buffName}");
            }
            else
            {
                Debug.LogError($"【BuffRandomEnemies】给 {prefab.name} 添加 {buffType.Name} 失败");
            }
        }
        Debug.Log("【BuffRandomEnemies】本轮 Buff 加挂完成");
    }

}
